/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package io.renren.modules.sys.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlHelper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.annotation.DataFilter;
import io.renren.common.utils.Constant;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.sys.dao.SysUserDao;
import io.renren.modules.sys.entity.SysDeptEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysDeptService;
import io.renren.modules.sys.service.SysUserRoleService;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.shiro.ShiroUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 系统用户
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年9月18日 上午9:46:09
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysDeptService sysDeptService;

	@Override
	public List<Long> queryAllMenuId(Long userId) {
		return baseMapper.queryAllMenuId(userId);
	}

	@Override
	//@DataFilter(subDept = true, user = false)
	public PageUtils queryPage(Map<String, Object> params) {
		String username = (String)params.get("username");
		Page<SysUserEntity> page = (Page<SysUserEntity>) this.page(
			new Query<SysUserEntity>(params).getPage(),
			new QueryWrapper<SysUserEntity>()
				.eq(params.get("sellerId") !=null ,"seller_id",params.get("sellerId"))
				.like(StringUtils.isNotBlank(username),"username", username)
				.apply(params.get(Constant.SQL_FILTER) != null, (String)params.get(Constant.SQL_FILTER))
		);

//		for(SysUserEntity sysUserEntity : page.getRecords()){
//			SysDeptEntity sysDeptEntity = sysDeptService.getById(sysUserEntity.getDeptId());
//			sysUserEntity.setDeptName(sysDeptEntity.getName());
//		}

		return new PageUtils(page);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveSysUser(SysUserEntity user) {
		user.setCreateTime(new Date());
		//sha1加密
		user.setPasswordOld(user.getPassword());
		user.setPassword(ShiroUtils.sha1(user.getPassword()));
		this.save(user);
		
		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(SysUserEntity user) {
		if(StringUtils.isBlank(user.getPassword())){
			user.setPassword(null);
		}else{
			user.setPasswordOld(user.getPassword());
			user.setPassword(ShiroUtils.sha1(user.getPassword()));
		}
		this.updateById(user);
		
		//保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}


	@Override
	public boolean updatePassword(Long userId, String newPassword) {
        SysUserEntity userEntity = new SysUserEntity();
        userEntity.setPassword(ShiroUtils.sha1(newPassword));
		userEntity.setPasswordOld(newPassword);
        return this.update(userEntity,
                new UpdateWrapper<SysUserEntity>().eq("user_id", userId));
    }

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void changePassword() {
		List<SysUserEntity> list = baseMapper.selectList(new QueryWrapper<SysUserEntity>()
													.eq("merchant_type",1));

		for (int i=0; i<list.size(); i++){
			SysUserEntity sysUserEntity = list.get(i);

			if(sysUserEntity.getSellerId() == null || sysUserEntity.getSellerId() <= 0){
				System.out.println("============ 用户："+sysUserEntity.getUsername()+"，未获取到商户ID ==========");
				continue;
			}
			// 创建部门
			SysDeptEntity sysDeptEntity = sysDeptService.getOne(new QueryWrapper<SysDeptEntity>()
					.eq("seller_id",sysUserEntity.getSellerId())
			);
			if(sysDeptEntity == null){
				sysDeptEntity = new SysDeptEntity();
				sysDeptEntity.setName(sysUserEntity.getUsername());
				sysDeptEntity.setParentId(0L);
				sysDeptEntity.setSellerId(sysUserEntity.getSellerId());

				sysDeptService.save(sysDeptEntity);
				System.out.println("============ 部门："+sysUserEntity.getUsername()+"，创建成功 ==========");
			}
			// 修改密码
			sysUserEntity.setPassword(ShiroUtils.sha1(sysUserEntity.getPasswordOld()));
			this.updateById(sysUserEntity);
			System.out.println("============ 用户："+sysUserEntity.getUsername()+"，密码修改成功 ==========");
		}
	}

	@Override
	public boolean updateByMap(Map<String, Object> updateMap, Long userId) {
		int update = this.baseMapper.updateByMap(updateMap, userId);
		if (update == 0){
			return false;
		}
		return true;
	}

	@Override
	public List<SysUserEntity> getAcceptOrderUserlist(Long sellerId) {
		return  this.baseMapper.getAcceptOrderUserlist(sellerId);
	}

	@Override
	public void updateBatchByMap(Map<String, Object> map, List<Long> userIds) {
		baseMapper.updateBatchByMap(map, userIds);
	}

}
